module("ServerSelectUI", package.seeall)

local recent_servers = {
	{ caption = "内侧998区：八雄争霸（新）", status = "爆满" }
}

local servers = {
	{ caption = "内侧998区：八雄争霸（新）", status = "新区" },
	{ caption = "内侧997区：八雄争霸", status = "爆满" },
	{ caption = "内侧996区：八雄争霸", status = "爆满" },
	{ caption = "内侧995区：八雄争霸", status = "爆满" },
}

function create(scene)
	local self = ccs.GUIReader:getInstance():widgetFromJsonFile("res/UI/LoginUI/ServerSelectUI.ExportJson")
	self._loginScene = scene
	init(self)
	return self
end

function onButtonServerClick(self, server)
	LoginScene.server = server
	LoginScene.showUILayer(self._loginScene, LoginHomeUI)
end

function updateServerList(self, serverlist)
	for k,v in ipairs(serverlist) do
		self._listview:pushBackDefaultItem()
		local item = self._listview:getItem(k-1)
		local button = item:getChildByName("Button_Server")
		local labelCaption = button:getChildByName("Label_Caption")
		local labelStatus = button:getChildByName("Label_Status")
		labelCaption:setText(v.caption)
		labelStatus:setText(v.status)
		button:addTouchEventListener(function(sender, eventType)
			if (eventType == ccui.TouchEventType.ended) then
				deferredCall(function()
	            		onButtonServerClick(self, v)
	            	end, 0)
				end
			end
		)
	end
end

function init(self)
	self._buttonRecent = self:getChildByName("Panel_Recent"):getChildByName("Button_Recent")
	self._labelRecentName = self._buttonRecent:getChildByName("Label_Name")
	self._labelRecentStatus = self._buttonRecent:getChildByName("Label_Status")

	self._listview = self:getChildByName("Panel_List"):getChildByName("ListView_Server")

	local listmodel = ccs.GUIReader:getInstance():widgetFromJsonFile("res/UI/LoginUI/ServerSelectCell.ExportJson")
	local itembutton = listmodel:getChildByName("Button_Server")
	listmodel:setSize(itembutton:getSize())

	self._buttonRecent:addTouchEventListener(
		function(sender, eventType)
			if (eventType == ccui.TouchEventType.ended) then
				onButtonServerClick(self, recent_servers[1])
			end
		end)
 	
 	self._listview:setDirection(ccui.ScrollViewDir.vertical)
	self._listview:setItemModel(listmodel)

	updateServerList(self, servers)
	self._labelRecentName:setText(recent_servers[1].caption)
	self._labelRecentStatus:setText(recent_servers[1].status)
end